/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-簿记详情 4-指令详情
    info：type=3时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, codeType, FirstHeaderC } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
import { connect } from 'dva';
import investmentTypeData from '../../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../../utils/commonFunc';

class EftBuySellC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    productOnChange: () => {},
    portfolioOnChange: () => {},
    tradingcodeOnChange: () => {},
  };
  state = {
    info: undefined, //etf详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    jyfx: /^[1-9]\d*$/, //校验规则 与交易方向有关 可变更
    isCanOrder: true, //是否可以下达 默认可以下达
    typeStuas: false, // 交易类型 市价为true，默认限价
    exchangecode: undefined,
    tradingcode: undefined,
    marketPrice: undefined, //市价
    feeData: {
      //费用自动计算条件
      productId: undefined,
      portfolioid: undefined,
      tradingCode: undefined,
      exchangecode: undefined,
      sectype: 'fund',
      trademarket: 'jjpt',
      orderside: undefined,
      price: undefined,
    },
    directionType: '1',
  };
  componentDidMount() {
    this.props.onRef(this);
  }
  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 4) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, exchangecode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, exchangecode: data.exchangeCode } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        }
      }
    }, 100);
  };
  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
    if (val && (this.props.type == 1 || this.props.etfType)) {
      //新增指令时 需要判断该组合是否进行了指令配置
      this.props.dispatch({
        type: 'isAccountConfiguredM/queryIsAccountConfigured',
        payload: {
          portId: val,
          etfType: this.props.etfType,
        },
        callback: (data) => {
          if (data.result) {
            this.setState({
              isCanOrder: true,
            });
          } else {
            this.setState({
              isCanOrder: false,
            });
            message.warning(data.msg);
          }
        },
      });
    } else if (!val && this.props.type == 1) {
      this.setState({
        isCanOrder: true,
      });
    }
  };
  //产品改变
  productOnChange = (value) => {};

  jyfxSelect = (e) => {
    if (this.props.info) return; //详情时不再进行校验
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    this.changeFee('orderside', e?.value);
    if (e && e.value == 1) {
      this.setState(
        {
          jyfx: /^[1-9]\d*00$/,
        },
        () => {
          setFieldsValue({
            amount: undefined,
          }); //重新校验数量
        },
      );
      setFieldsValue({
        investmentType: 'FVTPL',
      });
    } else {
      this.setState(
        {
          jyfx: /^[1-9]\d*$/,
        },
        () => {
          setFieldsValue({
            amount: undefined,
          }); //重新校验数量
        },
      );
      setFieldsValue({
        investmentType: this.props.position?.investmentType,
      });
    }
    this.setState({ directionType: e?.value });
  };
  calculateAmount = (val, type) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.formGroupThis.props;
    let price = getFieldValue('price');
    let amount = getFieldValue('amount');
    if (type == 'price') {
      price = val;
    } else {
      amount = val;
    }

    if (price && price != '' && amount && amount != '') {
      const zlprice = price * amount;
      setFieldsValue({
        zlprice: zlprice,
      });
      this.changeFee('price', zlprice);
    } else {
      setFieldsValue({
        zlprice: undefined,
      });
      this.changeFee('price', undefined);
    }
  };
  //证券代码改变时根据交易方向更改投资类型
  changeinvestmentType = () => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.formGroupThis.props;
    if (getFieldValue('direction') == 2) {
      setFieldsValue({
        investmentType: this.props.position?.investmentType,
      });
    } else {
      setFieldsValue({
        investmentType: 'FVTPL',
      });
    }
  };

  //证券代码切换
  securitiesCodeChange = (value) => {
    const { info } = this.props;
    const {
      form: { setFieldsValue, getFieldValue, resetFields },
    } = this.formGroupThis.props;
    if (info) return; //详情时不进入判断
    resetFields(['exchangeCode']);
    if (value) {
      this.props.tradingcodeOnChange(
        //抛出证券代码和交易市场
        {
          exchangecode: `${value.exchangeCode}`,
          tradingcode: `${value.tradingCode}`,
          secuabbr: value.secuabbr,
        },
      );
      setFieldsValue({
        exchangeCode: `${value.exchangeCode}`,
      });
      this.setState(
        {
          exchangecode: value.exchangeCode,
          tradingcode: value.tradingCode,
        },
        () => {
          if (getFieldValue('type') == 1) {
            this.typeOnChange({ value: '1' });
          }
        },
      );
    } else {
      this.props.tradingcodeOnChange({});
      setFieldsValue({ price: '' });
      this.setState({
        exchangecode: undefined,
        tradingcode: undefined,
      });
    }
  };
  //交易类型改变响应
  typeOnChange = (e) => {
    const { exchangecode, tradingcode } = this.state;
    const { dispatch, info } = this.props;
    const {
      form: { setFieldsValue, getFieldValue },
    } = this.formGroupThis.props;
    if (e && e.value == '1') {
      this.setState({
        typeStuas: true,
      });
      if (info) return; //详情时不进入判断
      if (exchangecode && tradingcode) {
        dispatch({
          type: 'etfOrderM/getHardenPrice',
          payload: {
            tradingcode,
            exchangecode,
          },
          callback: (data) => {
            if (data) {
              this.setState({
                marketPrice: data.price,
              });
              setFieldsValue({
                zlprice: +data.price * getFieldValue('amount'),
                price: data.price,
              });
              this.changeFee('price', +data.price * getFieldValue('amount'));
            } else {
              this.setState({
                marketPrice: '',
              });
              setFieldsValue({
                zlprice: '',
                price: '',
              });
            }
          },
        });
      } else {
        setFieldsValue({
          zlprice: '',
          price: '',
        });
        this.changeFee('price', undefined);
      }
    } else {
      this.setState({
        typeStuas: false,
      });
      if (info) return; //详情时不进入判断
      setFieldsValue({ price: '' });
    }
  };
  //投资类型下拉变更事件
  investmentChange = (e) => {};
  //form表单渲染
  formRender = () => {
    const { etfType, type, info, proposalType } = this.props;
    let disabled;
    if (type == 1 || type == 2 || type == 11) {
      disabled = false;
    } else {
      disabled = true;
    }

    return (
      <FormGroup
        dataSource={[
          {
            title: ['产品', '组合'],
            dataIndex: ['productid', 'portfolioid'],
            type: DATA_ENTRY.PRODUCTGROUPSEP,
            initialValue: info ? [info.productid, info.portfolioid] : undefined,
            authority: 'write',
            multipleGroup: false,
            disabled: disabled,
            rules: [[{ required: true, message: '请选择产品' }], [{ required: true, message: '请选择组合' }]],
            groupOnChange: (e) => {
              this.groupOnChange(e);
              this.changeFee('portfolioid', e?.key);
              this.props.portfolioCode && this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
            },
            productOnChange: (e) => {
              this.productOnChange(e);
              this.changeFee('productId', e?.key);
              this.props.productCode && this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
            },
            allowClear: false,
            maatApi: proposalType ? true : false,
            exist: 1,
            span: 16,
            controlLabelSpan: 6,
            tradeModel: this.props.tradeModel || type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined,
          },
          {
            dataIndex: 'zqdm',
            title: '证券代码',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: info ? `${info.exchangeCode}-${info.tradingcode}` : undefined,
            onChange: (e) => {
              this.securitiesCodeChange(e);
              this.changeFee('tradingCode', e ? e : undefined);
            },
            codeType: codeType.etf,
            rules: [{ required: true, message: '请选择证券代码' }],
            disabled: disabled,
            span: 8,
            controlLabelSpan: 6,
          },
          {
            title: '交易市场', // 显示名称
            dataIndex: 'exchangeCode', // Form识别的Item ID
            type: DATA_ENTRY.TRADINGMARKET,
            disabled: true,
            initialValue: info ? info.exchangeCode : undefined,
            rules: [{ required: true, message: '请选择' }],
            span: 8,
            controlLabelSpan: 6,
            onRef: (ref) => (this.formGroupThis = ref),
          },
          {
            title: '交易方向', // 显示名称
            dataIndex: 'direction', // Form识别的Item ID
            businessType: '9',
            type: DATA_ENTRY.TRADINGDIRECT,
            initialValue: info ? info.direction : undefined,
            onChange: this.jyfxSelect,
            disabled: disabled,
            rules: [{ required: true, message: '请选择交易方向!' }],
            span: 8,
            controlLabelSpan: 6,
          },
          {
            title: '交易类型', // 显示名称
            dataIndex: 'type', // Form识别的Item ID
            type: DATA_ENTRY.TRADINGTYPE,
            initialValue: info ? info.type : '2',
            disabled: type == 1 || etfType ? false : true,
            rules: [{ required: true, message: '请选择交易类型!' }],
            onChange: this.typeOnChange,
            span: 8,
            controlLabelSpan: 6,
          },
          {
            dataIndex: 'price',
            type: DATA_ENTRY.INPUTNUMBER,
            title: proposalType ? '价格' : type == 1 || type == 4 ? '委托价格' : '成交价格',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.price : undefined,
            splitStyle: true,
            rules: this.state.typeStuas ? [] : [{ required: true, message: proposalType ? '请输入价格' : type == 1 || type == 4 ? '委托价格' : '成交价格' }],
            onChange: (val) => this.calculateAmount(val, 'price'),
            precision: 3,
            disabled: this.state.typeStuas ? true : disabled,
            unit: '元',
            span: 8,
            controlLabelSpan: 6,
          },
          {
            dataIndex: 'amount',
            type: DATA_ENTRY.INPUTNUMBER,
            title: proposalType ? '数量' : type == 1 || type == 4 ? '委托数量' : '成交数量',
            unit: '股',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.amount : undefined,
            splitStyle: true,
            onChange: (val) => this.calculateAmount(val, 'amount'),
            rules: [
              { required: true, message: proposalType ? '请输入数量' : type == 1 || type == 4 ? '请输入委托数量' : '请输入成交数量' },
              { pattern: this.state.jyfx, message: this.state.directionType == '1' ? '请输入100的倍数' : '数量必须大于0' },
            ],
            disabled: disabled,
            span: 8,
            controlLabelSpan: 6,
          },
          {
            dataIndex: 'zlprice',
            type: DATA_ENTRY.INPUTNUMBER,
            title: proposalType ? '指令金额' : type == 1 || type == 4 ? '委托金额' : '成交金额',
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.parValueTotal : undefined,
            splitStyle: true,
            rules: this.state.typeStuas ? [] : [{ required: true, message: proposalType ? '请输入指令金额' : type == 1 || type == 4 ? '请输入委托金额' : '请输入成交金额' }],
            precision: 3,
            disabled: this.state.typeStuas ? true : true,
            span: 8,
            controlLabelSpan: 6,
          },
          {
            title: '投资类型',
            dataIndex: 'investmentType',
            type: DATA_ENTRY.SELECT,
            initialValue: info ? info.investmentType : 'FVTPL',
            disabled: type == '3' || type == '4' ? true : this.state.directionType == 2 ? true : false,
            dataSource: investmentTypeData,
            allowClear: true,
            rules: [{ required: false, message: '请选择' }],
            onChange: this.investmentChange,
            span: 8,
            controlLabelSpan: 6,
          },
          // {
          //   title: '费用',
          //   dataIndex: 'fee',
          //   type: DATA_ENTRY.INPUTNUMBER,
          //   placeholder: "请输入",
          //   min: 0,
          //   precision: 2,
          //   initialValue: info ? info.fee : '',
          //   splitStyle: true,
          //   disabled: type == '3' || type == '4' ? true : false,
          //   unit: '元',
          //   span: 8,
          // controlLabelSpan:6,
          // },
          {
            dataIndex: 'remark',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: disabled,
            initialValue: info ? info.remark : undefined,
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
            controlLabelSpan: 2,
          },
        ]}
        autoLayout={false}
      />
    );
  };

  render() {
    return (
      <div>
        {this.props.proposal ? null : this.props.type < '3' && <FirstHeaderC title={'交易要素'} />}
        <div className={'grayBg'}>{this.formRender()}</div>
      </div>
    );
  }
}
export default connect(({ etfOrderM, isAccountConfiguredM, userM: user, loading }) => ({
  etfOrderM,
  isAccountConfiguredM,
  user,
  loading,
}))(Form.create()(EftBuySellC));
